// 引入express 应用开发框架
const express = require('express');
// 引入bodyParser库 来处理POST请求
const bodyParser = require('body-parser');
// 引入读取文件的中间件: readFileSync 同步读取文件
const { readFileSync } = require('fs');
// 找到绝对路径： resole 拼接路径
const { resolve } = require('path');

// 将数据库连接导入
const db = require('./utils/database');

const app = express();
var myResult = [];
var text;

// .execute 执行相对应的SQL命令
db.execute('SELECT * FROM demo_user').then((result) => {
    text = result[0];
}).catch((err) => {
    console.log(err);
});

// app.use() 接收中间件处理函数  extended: true 定义是否处理非标准的请求
// 处理中间件 bodyParser.urlencoded -实现Post请求传递数据 表单序列化
// 顺序必须在使用路由前面
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 允许跨域请求
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-methods', 'GET,POST');
    next();
});

// API开始啦

// const questionRoutes = require('./routes/question.js');
// app.use('/', questionRoutes);
app.post('/getQuestion', function (req, res) {
    const order = req.body.order;
    const questionData = JSON.parse(readFileSync(resolve(__dirname, 'data/question.json'), 'utf-8'));
    const questionResult = questionData[order];

    if (questionResult) {
        const { id, question, items } = questionResult;
        res.send({
            errorCode: 0,
            msg: 'OK',
            data: {
                id,
                question,
                items,
            },
            text: text
        });
    } else {
        res.send({
            errorCode: 1,
            msg: 'NO-DATA',
            data: myResult
        });

        myResult = [];
    }
});

const answerRoutes = require('./routes/answer');
app.use(answerRoutes);
// app.post('/uploadAnswer', function (reg, res) {
//     const { order, myAnswer } = reg.body;
//     const questionData = JSON.parse(readFileSync(resolve(__dirname, 'data/question.json'), 'utf-8'));
//     const { id, question, items, answer } = questionData[order];
//     myResult.push({
//         qId: id,
//         question,
//         myAnswer: items[myAnswer],
//         rightAnswer: items[answer],
//         isTrue: myAnswer == answer
//     });

//     res.send({
//         errorCode: 0,
//         msg: 'OK'
//     })
// });
// API结束啦

// 监听的端口
app.listen(8090);




